package com.flmz.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flmz.common.core.constants.Constants;
import com.flmz.common.core.domain.TableDataInfo;
import com.flmz.friend.domain.question.Question;
import com.flmz.friend.domain.question.dto.QuestionQueryDTO;
import com.flmz.friend.domain.question.es.QuestionES;
import com.flmz.friend.domain.question.vo.QuestionDetailVO;
import com.flmz.friend.domain.question.vo.QuestionVO;
import com.flmz.friend.elasticsearch.QuestionRepository;
import com.flmz.friend.manager.QuestionCacheManager;
import com.flmz.friend.mapper.question.QuestionMapper;
import com.flmz.friend.mapper.user.UserSubmitMapper;
import com.flmz.friend.service.question.IQuestionService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {

	@Autowired
	private QuestionRepository questionRepository;

	@Autowired
	private QuestionMapper questionMapper;

	@Autowired
	private UserSubmitMapper userSubmitMapper;

	@Autowired
	private QuestionCacheManager questionCacheManager;

	@Override
	public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
		long count = questionRepository.count();
		// es中不包含数据，那就查数据库并存入es
		if (count <= 0) {
			refreshQuestion();
		}

		Sort sort = Sort.by(Sort.Direction.DESC, "createTime"); // 按照创建时间排序
		Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
		Integer difficulty = questionQueryDTO.getDifficulty();
		String keyword = questionQueryDTO.getKeyword();
		Page<QuestionES> questionESPage;
		// 四种查询方式，两个都为空，一个空一个不空，两个都为不空
		if (difficulty == null && StrUtil.isEmpty(keyword)) {
			questionESPage = questionRepository.findAll(pageable);
		} else if (StrUtil.isEmpty(keyword)) {
			questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
		} else if (difficulty == null) {
			questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
		} else {
			questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
		}

		long total = questionESPage.getTotalElements();
		if (total <= 0) {
			return TableDataInfo.empty();
		}

		List<QuestionES> questionESList = questionESPage.getContent();
		List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
		return TableDataInfo.success(questionVOList, total);
	}

	@Override
	public QuestionDetailVO detail(Long questionId) {
		// 先去es中查询
		QuestionES questionES = questionRepository.findById(questionId).orElse(null);
		QuestionDetailVO questionDetailVO = new QuestionDetailVO();
		if (questionES != null) {
			BeanUtil.copyProperties(questionES, questionDetailVO);
			return questionDetailVO;
		}

		// 从数据库中查询
		Question question = questionMapper.selectById(questionId);
		if (question == null) {
			return null;
		}
		refreshQuestion();
		BeanUtil.copyProperties(question, questionDetailVO);
		return questionDetailVO;
	}

	// 题目的顺序列表，当前题目是哪个（questionId）
	// 先从redis中查询，没有就查数据库（管理端在新增删除题目时会维护）
	// redis   key：q:l  value：questionId
	@Override
	public String preQuestion(Long questionId) {
		Long listSize = questionCacheManager.getListSize();
		if (listSize == null || listSize <= 0) {
			questionCacheManager.refreshCache();
		}
		return questionCacheManager.preQuestion(questionId).toString();
	}

	@Override
	public String nextQuestion(Long questionId) {
		Long listSize = questionCacheManager.getListSize();
		if (listSize == null || listSize <= 0) {
			questionCacheManager.refreshCache();
		}
		return questionCacheManager.nextQuestion(questionId).toString();
	}

	@Override
	public List<QuestionVO> hotList() {
		Long total = questionCacheManager.getHostListSize();
		List<Long> hotQuestionIdList;
		if (total == null || total <= 0) {
			PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
			hotQuestionIdList = userSubmitMapper.selectHostQuestionList();
			questionCacheManager.refreshHotQuestionList(hotQuestionIdList);
		} else {
			hotQuestionIdList = questionCacheManager.getHostList();
		}
		return assembleQuestionVOList(hotQuestionIdList);
	}

	private void refreshQuestion() {
		List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
		if (CollectionUtil.isEmpty(questionList)) {
			return;
		}
		// 同步到es中
		List<QuestionES> questionESList = BeanUtil.copyToList(questionList, QuestionES.class);
		questionRepository.saveAll(questionESList);
	}

	private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
		if (CollectionUtil.isEmpty(hotQuestionIdList)) {
			return new ArrayList<>();
		}
		List<QuestionVO> resultList = new ArrayList<>();
		for (Long questionId : hotQuestionIdList) {
			QuestionVO questionVO = new QuestionVO();
			QuestionDetailVO detail = detail(questionId);
			questionVO.setTitle(detail.getTitle());
			resultList.add(questionVO);
		}
		return resultList;
	}
}
